import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {MaintenanceService} from '../../maintenance.service';
import {ActivatedRoute, Router} from '@angular/router';
import {StorageService} from '../../../services/storage.service';
import {PublicService} from '../../../services/public.service';
import {PUblicMethod} from '../../../services/PUblicMethod';
import {environment} from '../../../../environments/environment';
import {EventBusService} from '../../../services/event-bus.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MatenanceObjModel} from '../../matenanceObj.model';

@Component({
  selector: 'app-malfunction-accept-edit',
  templateUrl: './malfunction-accept-edit.component.html',
  styleUrls: ['./malfunction-accept-edit.component.scss']
})
export class MalfunctionAcceptEditComponent implements OnInit {
    formObj: MatenanceObjModel;
    options: Object = {
        '来源': [],
        '影响度': [],
        '紧急度': [],
        '故障级别': [],
        '所属系统': [],
        'departments': [],
    };
    defaultOption: Object = {
        'fromx': null,
        'influence': null,
        'urgency': null,
        'level': null,
        'bt_system': null,
        'acceptor': null
    };
    display: boolean = false;
    departementDisplay: boolean;           // 树显示控制
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    displayPersonel: boolean;              // 人员组织组件是否显示
    myForm: FormGroup;
    zh: Object;
    message: Message[] = [];               // 交互提示弹出框
    ip: string;
    formTitle = '创建故障单';
    uploadedFiles: any[] = [];
    maxDate: Date;

    constructor(private maintenanceService: MaintenanceService,
                private router: Router,
                private activatedRouter: ActivatedRoute,
                private storageService: StorageService,
                private publicService: PublicService,
                private fb: FormBuilder,
                private eventBusService: EventBusService) {
    }

    ngOnInit() {
        this.initForm();
        this.formObj = new MatenanceObjModel();
        this.zh = new PUblicMethod().initZh();
        this.maxDate = new Date();
        this.getOptions();
        this.formObj.status = '新建';
        this.formTitle = '新建故障单';
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
        this.formObj.create_time = PUblicMethod.formateEnrtyTime(new Date());
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime(new Date());
        (!this.formObj.sid) && (this.getDepPerson());
        this.ip = environment.url.management;
        this.displayPersonel = false;
        if (this.formObj.sid) {
            this.formTitle = '编辑故障单';
            this.getTirckMessage(this.formObj.sid);
            this.maintenanceService.getFlowChart(this.formObj.status).subscribe(res => {
                this.eventBusService.maintenance.next(res);
            });
            this.formObj.acceptor = '222222';
        }
    }
    goBack() {
        this.router.navigate(['../malfunctionOverview'], {relativeTo: this.activatedRouter});
    }
    getOptions() {
        this.maintenanceService.getParamOptions().subscribe(res => {
            this.options = res;
            this.getPrority(res['影响度'][0]['name'], res['紧急度'][0]['name']);
            this.formObj.fromx = res['来源'][0]['name'];
            this.formObj.level = res['故障级别'][0]['name'];
            this.formObj.bt_system = res['所属系统'][0]['name'];
            this.formObj.influence = res['影响度'][0]['name'];
            this.formObj.urgency = res['紧急度'][0]['name'];
        });
    }
    initForm() {
        this.myForm = this.fb.group({
            'submitter': '',
            'title': '',
            'content': '',
            'acceptor': ''
        });
    }
    showTreeDialog( opType ) {
        switch (opType) {
            case 'submitter':
                this.displayPersonel = true;
                break;
            case 'department':
                this.display = true;
                this.publicService.getDepartmentDatas().subscribe(res => {
                    this.filesTree4 = res;
                });
        }

    }
    clearTreeDialog(opType) {
        switch (opType) {
            case 'submitter':
                this.formObj.submitter = '';
                this.formObj.submitter_pid = '';
                this.formObj.submitter_org_oid = '';
                this.formObj.submitter_org = '';
                this.formObj.submitter_phone = '';
                break;
            case 'department':
                this.formObj.acceptor = '';
                this.formObj.acceptor_org = '';
                this.formObj.acceptor_org_oid = '';
                this.formObj.acceptor_pid = '';
                break;
        }

    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.acceptor_org = this.selected['label'];
        this.formObj.acceptor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    dataEmitter(event) {
        this.formObj.submitter = event.name;
        this.formObj.submitter_pid = event.pid;
        this.formObj.submitter_org_oid = event.oid;
        this.formObj.submitter_org = event.organization;
        this.formObj.submitter_phone = event.mobile;
    }
    displayEmitter(event) {
        this.displayPersonel = event;
    }
    onFocus() {
        if (this.formObj.influence['name']) {
            this.formObj.influence = this.formObj.influence['name'];
        }
        if (this.formObj.urgency['name']) {
            this.formObj.urgency = this.formObj.urgency['name'];
        }
        this.getPrority(this.formObj.influence, this.formObj.urgency);
    }
    getPrority(influency, urgency) {
        if ( influency && urgency ) {
            this.maintenanceService.getPrority( influency, urgency ).subscribe(res => {
                if (res) {
                    this.formObj.priority = res['priority'];
                    this.getDeadline(influency, urgency, res['priority']);
                }
            });
        }
    }
    getDeadline(influency, urgency, prority) {
        if ( influency && urgency && prority ) {
            this.maintenanceService.getDeadline( influency, urgency, prority, this.formObj.create_time).subscribe(res => {
                if (res) {
                    this.formObj.deadline = res['time_deadline'];
                }
            });
        }
    }
    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
    }
    onUpload(event) {
        let xhrRespose = JSON.parse(event.xhr.response);
        if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
            this.formObj.attachments = xhrRespose['datas'];
            this.message = [];
            this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
        }else {
            this.message = [];
            this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
        }
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.options['departments'] = newArray;
                this.formObj.acceptor_pid = newArray[0]['value']['pid'];
                this.formObj.acceptor = newArray[0]['value']['name'];
            }
        });
    }
    onChange(event) {
        this.formObj.acceptor = event['value']['name'];
        this.formObj.acceptor_pid = event['value']['pid'];
    }
    save() {
        this.addSelectedName();
        this.filterOptionName();
        this.resetOccurtime();
        this.maintenanceService.saveTicket( this.formObj ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '保存成功'});
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `保存失败${res}`});
            }
        });
    }
    resetOccurtime() {
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime(this.formObj.occurrence_time);
    }
    addSelectedName() {
        (!this.formObj.fromx) && (this.formObj.fromx = this.defaultOption['fromx']);
        (!this.formObj.level) && (this.formObj.level = this.defaultOption['level']);
        (!this.formObj.bt_system) && (this.formObj.bt_system = this.defaultOption['bt_system']);
        (!this.formObj.influence) && (this.formObj.influence = this.defaultOption['influence']);
        (!this.formObj.urgency) && (this.formObj.urgency = this.defaultOption['urgency']);
        // (!this.formObj.acceptor) && (this.formObj.acceptor = this.defaultOption['acceptor']);
    }
    filterOptionName() {
        if (this.formObj.fromx['name']) {
            this.formObj.fromx = this.formObj.fromx['name'];
        }
        if (this.formObj.level['name']) {
            this.formObj.level = this.formObj.level['name'];
        }
        if (this.formObj.bt_system['name']) {
            this.formObj.bt_system = this.formObj.bt_system['name'];
        }
        if (this.formObj.influence['name']) {
            this.formObj.influence = this.formObj.influence['name'];
        }
        if (this.formObj.urgency['name']) {
            this.formObj.urgency = this.formObj.urgency['name'];
        }
        // if (this.formObj.acceptor['name']) {
        //     this.formObj.acceptor = this.formObj.acceptor['name'];
        // }
    }
    get Submitter() {
        return this.myForm.controls['submitter'].untouched && this.myForm.controls['submitter'].hasError('required');
    }
    get title() {
        return this.myForm.controls['title'].untouched && this.myForm.controls['title'].hasError('required');
    }
    get content() {
        // console.log('untouched', this.myForm.controls['content'].untouched);
        // console.log('required', this.myForm.controls['content'].hasError('required'));
        return this.myForm.controls['content'].untouched && this.myForm.controls['content'].hasError('required');
    }
    get acceptor() {
        // console.log('untouched', this.myForm.controls['content'].untouched);
        // console.log('required', this.myForm.controls['content'].hasError('required'));
        return this.myForm.controls['acceptor'].untouched && this.myForm.controls['acceptor'].hasError('required');
    }
    setValidators() {
        this.myForm.controls['submitter'].setValidators([Validators.required]);
        this.myForm.controls['title'].setValidators([Validators.required]);
        this.myForm.controls['content'].setValidators([Validators.required]);
        this.myForm.controls['submitter'].updateValueAndValidity();
        this.myForm.controls['title'].updateValueAndValidity();
        this.myForm.controls['content'].updateValueAndValidity();
    }
    submitTrick() {
        this.addSelectedName();
        this.filterOptionName();
        if ( !this.formObj.submitter
            || !this.formObj.title
            || !this.formObj.content
        ) {
            this.showError();
            this.setValidators();
        }else {
            this.formObj.status = '待分配';
            this.submitPost(this.formObj);
        }
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    submitPost(paper) {
        this.resetOccurtime();
        this.maintenanceService.submitTicket( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }
    submitAndDistribute() {
        this.addSelectedName();
        this.filterOptionName();
        if ( !this.formObj.submitter
            || !this.formObj.title
            || !this.formObj.content
            || !this.formObj.acceptor_org
        ) {
            this.showError();
            this.setValidators();
            this.myForm.controls['acceptor'].setValidators([Validators.required]);
            this.myForm.controls['acceptor'].updateValueAndValidity();
        }else {
            this.formObj.status = '待接受';
            this.submitPost(this.formObj);
        }
    }
    getTirckMessage(sid) {
        this.maintenanceService.getTrick(sid).subscribe(res => {
            this.formObj.sid = res['sid'];
            this.formObj.fromx = res['fromx'];
            this.formObj.status = res['status'];
            this.formObj.submitter = res['submitter'];
            this.formObj.submitter_pid = res['submitter_pid'];
            this.formObj.submitter_org_oid = res['submitter_org_oid'];
            this.formObj.submitter_org = res['submitter_org'];
            this.formObj.submitter_phone = res['submitter_phone'];
            this.formObj.occurrence_time = res['occurrence_time'];
            this.formObj.deadline = res['deadline'];
            this.formObj.influence = res['influence'];
            this.formObj.urgency = res['urgency'];
            this.formObj.priority = res['priority'];
            this.formObj.level = res['level'];
            this.formObj.bt_system = res['bt_system'];
            this.formObj.addr = res['addr'];
            this.formObj.title = res['title'];
            this.formObj.content = res['content'];
            this.formObj.service = res['service'];
            this.formObj.devices = res['devices'];
            this.formObj.acceptor_org = res['acceptor_org'];
            this.formObj.acceptor_org_oid = res['acceptor_org_oid'];
            this.formObj.acceptor = res['acceptor'];
            this.formObj.acceptor_pid = res['acceptor_pid'];
            this.formObj.create_time = res['create_time'];
            this.defaultOption['fromx'] = res['fromx'];
            this.defaultOption['influence'] = res['influence'];
            this.defaultOption['urgency'] = res['urgency'];
            this.defaultOption['level'] = res['level'];
            this.defaultOption['bt_system'] = res['bt_system'];
            // this.defaultOption['acceptor'] = res['acceptor'];
            // this.hasAccepterOrg(res['acceptor_org_oid']);
            this.clearDefaultOption();
        });
    }
    hasAccepterOrg(oid) {
        if (oid) {
            this.getDepPerson(oid);
        }
    }
    clearDefaultOption() {
        // this.formObj.acceptor && (this.formObj.acceptor = null);
        this.formObj.urgency && (this.formObj.urgency = null);
        this.formObj.fromx && (this.formObj.fromx = null);
        this.formObj.level && (this.formObj.level = null);
        this.formObj.bt_system && (this.formObj.bt_system = null);
        this.formObj.influence && (this.formObj.influence = null);
    }

}
